package com.muc.plugin.interceptor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

import org.dom4j.Element;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.openfire.IQRouter;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.muc.MUCEventListener;
import org.jivesoftware.openfire.muc.MUCRoom;
import org.jivesoftware.openfire.session.Session;
import org.jivesoftware.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;

/**
 * 
 * 实现永久房间，且当用户登录时实现像QQ一样自动加入房间
 * 
 * @author
 * 
 */
public class MultiUserChat implements  MUCEventListener {

	private static final Logger log = LoggerFactory.getLogger(MultiUserChat.class);

	private static final String ADD_MEMBER = "INSERT INTO ofMucMember (roomID,jid,nickname) VALUES (?,?,?)";
	private static final String SELECT_MEMBER = "SELECT * FROM ofMucMember WHERE jid = ? and roomID = ?";
	private XMPPServer server = XMPPServer.getInstance();
	private IQRouter router = XMPPServer.getInstance().getIQRouter();

	/**
	 * 创建房间
	 * @param roomJID JID of the room that was created.
	 */
	@Override
	public void roomCreated(final JID roomJID) {
		new Thread(){
			public void run() {
				try {
					sleep(1*1000);
					MUCRoom mucRoom = server.getMultiUserChatManager()
							.getMultiUserChatService(roomJID)
							.getChatRoom(roomJID.getNode());
					server.getMultiUserChatManager().getMultiUserChatService(roomJID).refreshChatRoom(mucRoom.getName());

					/**
					 * 构建iq的扩展包，用于发送用户创建房间的ID。
					 */
					IQ iq = new IQ(IQ.Type.result);
					iq.setID(UUID.randomUUID().toString());
					iq.setTo(roomJID);
					iq.setChildElement("muc", "xls:muc-user-create-room");
					//增加room和account信息
					Element room1 = iq.getChildElement().addElement("roomId");
					room1.setText(mucRoom.getID() + "");
					//发送出去
					router.route(iq);

					log.info(" @@@@@@@@@@@@@ 创建群组 result iq : " + iq.toXML() + " ; room create:"+ roomJID +"-----roomId:"+mucRoom.getID());


				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}


	/**
	 * 加入房间
	 * @param roomJID the JID of the room where the occupant has joined.
	 * @param user the JID of the user joining the room.
	 * @param nickname nickname of the user in the room.
	 */
	@Override
	public void occupantJoined(final JID roomJID, final JID user, final String nickname) {
		new Thread(){
			public void run() {
				try {
					sleep(2*1000);
					MUCRoom mucRoom = server.getMultiUserChatManager()
							.getMultiUserChatService(roomJID)
							.getChatRoom(roomJID.getNode());
					// 是否是永久房间
					if (mucRoom.isPersistent()) {
						// 当前用户是否已经存在
						if (!userExist(mucRoom.getID(),user)) {
							saveMember(mucRoom, user, user.getNode());
						}

						log.info("@@@@@@@@@@@@ 用户加入房间 RoomJid:"
								+ roomJID.toString() + ";roomId: "+ mucRoom.getID() +";UserJID:"
								+ user.toString() + ";nickname:" + nickname);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}


	/*
	 * 查找给定的JID用户是否存在
	 */
	public static boolean userExist(long roomId,JID bareJID) {
		boolean sign = false;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet resultSet;
		try {
			con = DbConnectionManager.getConnection();
			ps = con.prepareStatement(SELECT_MEMBER);
			ps.setString(1, bareJID.toBareJID());
			ps.setLong(2, roomId);
			resultSet = ps.executeQuery();
			if (resultSet.next()) {
				sign = true;
			}
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		} finally {
			DbConnectionManager.closeConnection(ps, con);
		}
		return sign;
	}

	/*
	 * 将加入房间的用户序列化到数据库中
	 */
	@SuppressWarnings("deprecation")
	public static void saveMember(MUCRoom mucRoom, JID bareJID, String resource) {
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = DbConnectionManager.getConnection();
			ps = con.prepareStatement(ADD_MEMBER);
			ps.setLong(1, mucRoom.getID());
			ps.setString(2, bareJID.toBareJID());
			ps.setString(3, resource);
			ps.executeUpdate();
		} catch (SQLException e) {
			Log.error(e.getMessage(), e);
		} finally {
			DbConnectionManager.closeConnection(ps, con);
		}
	}

	@Override
	public void roomDestroyed(JID roomJID) {
		log.info("@@@@@@@@@@@@@ room 销毁");
	}

	@Override
	public void occupantLeft(JID roomJID, JID user) {
		log.info("@@@@@@@@@@@@ 离开群组 :"+roomJID.toBareJID());
	}

	@Override
	public void nicknameChanged(JID roomJID, JID user, String oldNickname,
								String newNickname) {

	}

	@Override
	public void messageReceived(JID roomJID, JID user, String nickname,
								Message message) {

	}

	@Override
	public void privateMessageRecieved(JID toJID, JID fromJID, Message message) {

	}

	@Override
	public void roomSubjectChanged(JID roomJID, JID user, String newSubject) {

	}



	/*public static void refreshCache(long roomId){
		List<MultiUserChatService> list = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatServices();
		for (MultiUserChatService service:list) {
			List<MUCRoom> mucRooms =  service.getChatRooms();
			for (MUCRoom mucRoom :mucRooms) {
				long rId = mucRoom.getID();
				if(rId == roomId){
					JID roomJID = mucRoom.getJID();
					String roomName = mucRoom.getName();
					XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(roomJID).refreshChatRoom(roomName);
					Log.info("service.getServiceDomain() 缓存清除成功:"+service.getServiceDomain());
				}
			}

		}
	}*/

}
